package com.sc.sysconfig.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.sysconfig.dao.SysRoleMenuMapper;
import com.sc.sysconfig.dto.RoleQueryDTO;
import com.sc.sysconfig.entity.SysMenu;
import com.sc.sysconfig.entity.SysRole;
import com.sc.sysconfig.dao.SysRoleMapper;
import com.sc.sysconfig.entity.SysRoleMenu;
import com.sc.sysconfig.service.SysRoleService;
import com.sc.sysconfig.vo.OptionVO;
import com.sc.sysconfig.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 系统角色服务impl
 *
 * @author 徐赫阳
 * @date 2021/09/02
 */
@Service
@Component
public class SysRoleServiceImpl  extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    /**
     * 系统角色映射器
     */
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 获取角色列表
     *
     * @param queryDTO 查询dto
     * @return {@link PageVO}<{@link SysRole}>
     */
    @Override
    public PageVO<SysRole> getRoleList(RoleQueryDTO queryDTO){
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SysRole::getIsDel,0)
                .like(queryDTO.getName() != null,SysRole::getName,queryDTO.getName())
                .eq(queryDTO.getStatus()!= null,SysRole::getStatus,queryDTO.getStatus())
                .orderByAsc(SysRole::getId);
        Integer count = this.sysRoleMapper.selectList(queryWrapper).size();
        List<SysRole> list = this.sysRoleMapper.selectList(queryWrapper.lambda().last("LIMIT "+ (queryDTO.getPage() - 1) * queryDTO.getPageSize() + ","+ queryDTO.getPageSize()));
        for (SysRole role: list){
            QueryWrapper<SysRoleMenu> rmqw = new QueryWrapper<>();
            rmqw.lambda().eq(SysRoleMenu::getRoleId,role.getId());
            List<Integer> permission = sysRoleMenuMapper.selectList(rmqw)
                    .stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            role.setPermission(permission);
        }
        return PageVO.setPage(queryDTO.getPage(),queryDTO.getPageSize(),list,count);
    }

    /**
     * 得到所有的角色
     *
     * @return {@link List}<{@link SysRole}>
     */
    @Override
    public List<OptionVO> getAllRole(){
        return this.sysRoleMapper.selectAllRole();
    }

    /**
     * 得到角色的选择
     *
     * @return {@link List}<{@link OptionVO}>
     */
    @Override
    public List<OptionVO> getRoleOption(){
        return this.sysRoleMapper.selectRoleOption();
    }
}
